package com.ler.yrmall.utils;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @author Leron
 */
public class TxUtil {

    public static void doTransactionCompletion(TxCompletion tx) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(tx);
            return;
        }
        tx.runnable.run();
    }

    // example
    @Transactional(rollbackFor = Exception.class)
    public void example() {
        TxUtil.doTransactionCompletion(new TxCompletion(() -> {
            // do something
        }));
    }

    public static class TxCompletion implements TransactionSynchronization {

        private final Runnable runnable;

        public TxCompletion(Runnable runnable) {
            this.runnable = runnable;
        }

        @Override
        public void afterCompletion(int status) {
            if (status == TransactionSynchronization.STATUS_COMMITTED) {
                runnable.run();
            }
        }
    }

}